/*
 * Application.java
 *
 * Created on April 16, 2007, 6:15 PM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package org.voidness.twittava;

import java.util.Collection;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.cookie.CookiePolicy;
import org.apache.commons.httpclient.methods.PostMethod;
import org.voidness.twittava.config.ConfigurationManager;
import org.voidness.twittava.conversion.ConversionFactory;
import org.voidness.twittava.conversion.converters.Converter;
import org.voidness.twittava.domain.Status;
import org.voidness.twittava.gui.TwittavaWindow;

/**
 *
 * @author void
 */
public class Application {
    private HttpClient httpClient = null;
    
    public Application() {
        // Setup the http client
        httpClient = new HttpClient();
        
        // Setup authentication credentials
        httpClient.getState().setCredentials(
                new AuthScope("twitter.com", 80, "Twitter API"),
                new UsernamePasswordCredentials(
                    ConfigurationManager.getInstance().getProperty("username"), 
                    ConfigurationManager.getInstance().getProperty("password"))
                );
        
        // Set a 5 second timeout
        httpClient.getParams().setConnectionManagerTimeout(5000);
    }
    
    public Status postStatus(String string) throws Exception {
        // This is the statuses we will return
        Status newStatus = null;
        
        // We need a post method
        PostMethod post = new PostMethod("http://twitter.com/statuses/update.xml");
        setupHttpMethod(post);
                
        // Set the status
        post.addParameter("status", string);
        
        try {
            // Execute the post
            int status = httpClient.executeMethod(post);
            
            // If we get a status = ok then get the list
            if (status == 200) {
                // Everything went ok. New status published.
                Converter converter = ConversionFactory.getConverter(Converter.XML);
                newStatus = converter.convertStatus(post.getResponseBodyAsString());
            } else {
                // Throw an exception, because we didnt get a valid response from the server
                throw new Exception("Failed to receive status 200 from the server. Status was: " + status);
            }
        } finally {
            // release any connection resources used by the method
            post.releaseConnection();
        }
        
        // Return the new status
        return newStatus;
    }
    
    public Collection<Status> getFriendsTimeline() throws Exception {
        // This is the statuses we will return
        Collection<Status> statuses = null;
        
        // We need a post method
        PostMethod post = new PostMethod("http://twitter.com/statuses/friends_timeline.xml");
        setupHttpMethod(post);
        
        try {
            // Execute the post
            //int status = 200;
            int status = httpClient.executeMethod(post);
            
            // If we get a status = ok then get the list
            if (status == 200) {
                Converter converter = ConversionFactory.getConverter(Converter.XML);
                //statuses = ConversionFactory.getFooBarData();
                statuses = converter.convertTimeline(post.getResponseBodyAsString());
            } else {
                // Throw an exception, because we didnt get a valid response from the server
                throw new Exception("Failed to receive status 200 from the server. Status was: " + status);
            }
        } finally {
            // release any connection resources used by the method
            post.releaseConnection();
        }
        
        // Return the statuses
        return statuses;
    }
    
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        try {
            // Set system Java L&F
            UIManager.setLookAndFeel(
                    UIManager.getSystemLookAndFeelClassName());
        } catch (UnsupportedLookAndFeelException e) {
            // handle exception
        } catch (ClassNotFoundException e) {
            // handle exception
        } catch (InstantiationException e) {
            // handle exception
        } catch (IllegalAccessException e) {
            // handle exception
        }
        
        TwittavaWindow window = new TwittavaWindow();
        window.setVisible(true);
        new SystrayManager(window);
    }

    private void setupHttpMethod(PostMethod post) {
        // Setup headers and default parameters
        post.addRequestHeader("X-Twitter-Client", "Twittava");
        post.addRequestHeader("X-Twitter-Client-Version", "0.1");
        post.addRequestHeader("X-Twitter-Client-URL", "http://no.url.for.this.yet.:)");
        post.getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES);
        post.getParams().setSoTimeout(5000);
        
        // We also need to say we want authentication for this call
        post.setDoAuthentication(true);
    }
    
}
